#!/usr/bin/env python3
"""
Example usage of the digit-only OCR API endpoint
"""

import requests
from pathlib import Path

# API配置
API_BASE_URL = "http://localhost:8001"
DIGIT_OCR_ENDPOINT = "/api/ocr/digits"

def upload_and_recognize_digits(image_path, confidence_threshold=0.8, 
                               filter_spaces=True, filter_special_chars=True):
    """
    上传图片并进行数字识别
    
    Args:
        image_path: 图片文件路径
        confidence_threshold: 置信度阈值 (0.0-1.0)，默认0.8（数字识别使用较高阈值）
        filter_spaces: 是否过滤空格
        filter_special_chars: 是否过滤特殊字符
    
    Returns:
        dict: 数字识别结果
    """
    
    # 检查文件是否存在
    if not Path(image_path).exists():
        raise FileNotFoundError(f"图片文件不存在: {image_path}")
    
    # 准备请求参数
    params = {
        "confidence_threshold": confidence_threshold,
        "filter_spaces": filter_spaces,
        "filter_special_chars": filter_special_chars
    }
    
    # 上传文件并处理
    try:
        with open(image_path, 'rb') as f:
            files = {'file': (Path(image_path).name, f, 'image/png')}
            
            print(f"正在上传并识别数字: {image_path}")
            print(f"参数: confidence_threshold={confidence_threshold}")
            
            response = requests.post(
                f"{API_BASE_URL}{DIGIT_OCR_ENDPOINT}",
                files=files,
                params=params
            )
        
        # 处理响应
        if response.status_code == 200:
            result = response.json()
            return result
        else:
            raise Exception(f"API请求失败: {response.status_code} - {response.text}")
            
    except Exception as e:
        raise Exception(f"数字识别处理失败: {str(e)}")

def print_digit_results(result):
    """打印数字识别结果"""
    
    if not result['success']:
        print(f"❌ 识别失败: {result['message']}")
        return
    
    data = result['data']
    
    print("\n" + "="*60)
    print("🔢 数字识别结果")
    print("="*60)
    print(f"✅ 状态: {result['message']}")
    print(f"⏱️  处理时间: {data['processing_time']:.2f}秒")
    print(f"🌐 识别类型: {data['language_used']}")
    print(f"📊 平均置信度: {data['average_confidence']:.3f}")
    print(f"📝 总字符数: {data['total_characters']}")
    print(f"🔍 识别区域数: {len(data['results'])}")
    
    print(f"\n🔢 提取的数字:\n'{data['total_text']}'")
    
    if data['results']:
        print(f"\n📍 详细识别结果:")
        for i, item in enumerate(data['results'], 1):
            print(f"  {i}. 数字: '{item['text']}'")
            print(f"     置信度: {item['confidence']:.3f}")
            print(f"     坐标: {item['bbox']}")
            print()

def create_sample_digit_images():
    """创建示例数字图片"""
    print("📷 创建示例数字图片...")
    
    from PIL import Image, ImageDraw, ImageFont
    
    # 创建电话号码图片
    img1 = Image.new('RGB', (600, 150), color=(255, 255, 255))
    draw1 = ImageDraw.Draw(img1)
    
    try:
        font = ImageFont.truetype("arial.ttf", 36)
    except:
        font = ImageFont.load_default()
    
    draw1.text((50, 50), "Contact: +1 (555) 123-4567", fill=(0, 0, 0), font=font)
    img1.save("phone_number.png")
    print("✅ 电话号码图片已创建: phone_number.png")
    
    # 创建身份证图片
    img2 = Image.new('RGB', (600, 150), color=(255, 255, 255))
    draw2 = ImageDraw.Draw(img2)
    
    draw2.text((50, 50), "ID Number: 12345 67890", fill=(0, 0, 0), font=font)
    img2.save("id_number.png")
    print("✅ 身份证图片已创建: id_number.png")
    
    # 创建价格标签图片
    img3 = Image.new('RGB', (600, 150), color=(255, 255, 255))
    draw3 = ImageDraw.Draw(img3)
    
    draw3.text((50, 50), "Price: $99.99", fill=(0, 0, 0), font=font)
    img3.save("price_tag.png")
    print("✅ 价格标签图片已创建: price_tag.png")

def main():
    """主函数示例"""
    
    print("🔢 数字识别API使用示例")
    print("="*50)
    
    # 创建示例图片
    create_sample_digit_images()
    
    # 示例1: 电话号码识别
    try:
        print("\n📱 示例1: 电话号码识别")
        result = upload_and_recognize_digits(
            image_path="phone_number.png",
            confidence_threshold=0.8,
            filter_spaces=True,
            filter_special_chars=True
        )
        print_digit_results(result)
        
    except Exception as e:
        print(f"❌ 电话号码识别示例失败: {e}")
    
    # 示例2: 身份证号码识别（保留空格）
    try:
        print("\n🆔 示例2: 身份证号码识别（保留空格）")
        result = upload_and_recognize_digits(
            image_path="id_number.png",
            confidence_threshold=0.7,
            filter_spaces=False,  # 保留空格
            filter_special_chars=True
        )
        print_digit_results(result)
        
    except Exception as e:
        print(f"❌ 身份证识别示例失败: {e}")
    
    # 示例3: 价格识别（保留小数点）
    try:
        print("\n💰 示例3: 价格识别（保留小数点）")
        result = upload_and_recognize_digits(
            image_path="price_tag.png",
            confidence_threshold=0.6,
            filter_spaces=True,
            filter_special_chars=False  # 保留特殊字符（如小数点）
        )
        print_digit_results(result)
        
    except Exception as e:
        print(f"❌ 价格识别示例失败: {e}")
    
    print("\n" + "="*50)
    print("📚 数字识别API使用说明:")
    print("1. POST /api/ocr/digits - 上传图片进行数字识别")
    print("2. 支持参数:")
    print("   - confidence_threshold: 置信度阈值 (0.0-1.0，默认0.8)")
    print("   - filter_spaces: 是否过滤空格 (默认true)")
    print("   - filter_special_chars: 是否过滤特殊字符 (默认true)")
    print("3. 专门优化用于识别:")
    print("   - 电话号码")
    print("   - 身份证号码")
    print("   - 序列号")
    print("   - 价格")
    print("   - 测量数据")
    print("\n💡 提示:")
    print("   - 使用较高的置信度阈值(0.7-0.9)以获得更准确的数字识别")
    print("   - 根据需要调整过滤选项以保留必要的分隔符")

if __name__ == "__main__":
    main()